const router = require('koa-router')();


// 查询数据
router.get('/', async (ctx) => {
    let options = {}
    if (ctx.Model.modelName === 'Category') {
        options = { populate: 'parent' }
    }
    if (ctx.Model.modelName === 'Hero' || ctx.Model.modelName === 'Article') {
        require("../../models/Category")
        options = { populate: 'categories' }
    }
    const model = await ctx.Model.find({}).setOptions(options).limit(10)
    ctx.body = model
})

// 创建数据
router.post('/', async (ctx) => {
    const model = await ctx.Model.create(ctx.request.body)
    ctx.body = model
})

// 根据 ID 查询数据
router.get('/:id', async (ctx) => {
    ctx.body = await ctx.Model.findById(ctx.params.id)
})

// 编辑数据
router.post('/:id', async (ctx) => {
    await ctx.Model.findByIdAndUpdate(ctx.request.body.id, ctx.request.body)
    ctx.body = await ctx.Model.findById(ctx.request.body.id)
})

// 删除数据
router.delete('/:id', async (ctx) => {
    const model = await ctx.Model.findByIdAndRemove(ctx.params.id)
    ctx.body = model
})

module.exports = router